﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using TwitterStatisticsModel;

namespace App_Code
{
	/// <summary>
	/// Summary description for Collector
	/// </summary>
	public class Collector
	{
		private static List<Thread> threads = new List<Thread>();

		/// <summary>
		/// Collects and saves tweets for a given Keyword object in another thread
		/// </summary>
		/// <param name="keyword">SearchKeyword to collect tweets. Must be non-empty and not null</param>
		public static void CollectTweets(string keyword)
		{
			if (String.IsNullOrEmpty(keyword))
			{
				throw new ArgumentException();
			}
			Thread thread = new Thread(GetTweets);
			thread.Name = keyword;
			threads.Add(thread);
			thread.Start(keyword);
		}

		/// <summary>
		/// Stops collecting tweets for a given keyword
		/// </summary>
		/// <param name="keyword">Keyword, which tweet collecting should be stopped. Must by non-empty and not null</param>
		public static void StopCollecting(string keyword)
		{
			if (String.IsNullOrEmpty(keyword))
			{
				throw new ArgumentException();
			}
			var thread = (from th in threads where th.Name == keyword select th).FirstOrDefault();
			if (thread == null)
			{
				return;
			}
			thread.Abort();
			threads.Remove(thread);
		}

		private static void GetTweets(object keyword)
		{
			using (var entities = new TwitterEntities())
			{
				while (true)
				{
					try
					{
						List<TweetStored> tweets = JsonTwitterParser.GetTweets((string)keyword);
						var key = (from k in entities.Keywords where k.Keyword == (string) keyword select k).FirstOrDefault();
						var tweetIds = (from tw in key.Tweets select tw.TweetId).ToList();
						foreach (TweetStored tweet in tweets)
						{
							if (!tweetIds.Contains(tweet.TweetId))
							{
								tweet.Keywords.Add(key);
								entities.AddToTweets(tweet);
							}
						}
						entities.SaveChanges();
					}
					catch (Exception)
					{
						continue;
					}
					Thread.Sleep(60000);
				}
			}
		}
	}
}